package com.tma.timesheettracker.activity;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tma.timesheettracker.R;
import com.tma.timesheettracker.contentprovider.TimeTrackerContentProvider;
import com.tma.timesheettracker.model.Task;
import com.tma.timesheettracker.model.TrackingEntry;
import com.tma.timesheettracker.util.Util;

public class MainActivity extends Activity implements OnClickListener {
	private List<List<TrackingEntry>> m_sortEntriesbyDay = new ArrayList<List<TrackingEntry>>();
	private List<TrackingEntry> m_lstTimeSheetTracking = new ArrayList<TrackingEntry>();
	private List<TrackingEntry> m_lstPreviousTimeSheet = new ArrayList<TrackingEntry>();;
	private int m_durationPrevious = 0;
	private int m_oneHourSize = 0;
	private TextView m_lblToday;
	private TextView m_lblPreToday;
	private TextView m_historyValue;
	private ContentResolver m_resolver;
	private LinearLayout m_lnTimeSheet;
	private LinearLayout m_lnPreviousDay;
	private LinearLayout m_lnHistory;
	private ScrollView m_scrollView;
	private Date m_dayTracking;
	LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.MATCH_PARENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.fragment_main);
		m_resolver = getContentResolver();

		m_lblToday = (TextView) findViewById(R.id.lblToday);
		m_dayTracking = Calendar.getInstance().getTime();

		m_lblToday.setText(this.getString(R.string.today)
				+ Util.getDateFormat(m_dayTracking));

		m_lblPreToday = (TextView) findViewById(R.id.lblPreToday);

		m_lblPreToday.setText(Util.getDateFormat(Util.getPreviousDay()));

		m_scrollView = (ScrollView) findViewById(R.id.scrollTimesheet);
		m_historyValue = (TextView) findViewById(R.id.historyValue);
		m_lnTimeSheet = (LinearLayout) findViewById(R.id.lnTimesheet);
		m_lnPreviousDay = (LinearLayout) findViewById(R.id.lnPreTimeSheet);
		m_lnPreviousDay.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						PreviousActivity.class);
				intent.putExtra(Util.ONE_HOUR_SIZE, m_oneHourSize);
				intent.putExtra(Util.TIME_SHEET_TRACKING,
						(Serializable) m_lstPreviousTimeSheet);
				startActivityForResult(intent, PreviousActivity.REQUEST_CODE);
			}
		});
		m_lnHistory = (LinearLayout) findViewById(R.id.lnHistory);
		m_lnHistory.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						HistoryActivity.class);
				intent.putExtra(Util.ONE_HOUR_SIZE, m_oneHourSize);
				intent.putExtra(Util.SORTED_TIME_SHEET_TRACKING,
						(Serializable) m_sortEntriesbyDay);
				intent.putExtra(Util.TIME_SHEET_TRACKING,
						(Serializable) m_lstTimeSheetTracking);
				startActivityForResult(intent, HistoryActivity.REQUEST_CODE);
			}
		});

		try {
			getHistoryList();
			getPreviousDay();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		m_historyValue.setText(getHistoryPecent() + "%");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void addViewtoTimeSheet(int hourSize) throws ParseException {
		layoutParams.setMargins(10, 10, 10, 0);
		m_lstTimeSheetTracking = TimeTrackerContentProvider.TrackingEntryTable
				.getEntries(m_resolver, Util.formatDate(Util.getCurrentDay()));
		int count = 0;
		m_lnTimeSheet.removeAllViews();
		for (TrackingEntry entry : m_lstTimeSheetTracking) {
			if (entry.getDuration() != 0) {
				Button btn = new Button(this);
				btn.setOnClickListener(this);
				btn.setHeight(hourSize * entry.getDuration());
				btn.setGravity(Gravity.START);
				count += entry.getDuration();
				btn.setLayoutParams(layoutParams);
				btn.setBackgroundColor(this.getResources().getColor(
						R.color.green));
				// get task name
				Task task = TimeTrackerContentProvider.TaskTable.getTask(
						m_resolver, entry.getTask_id());
				Log.v("Task ID:", entry.getTask_id() + "");
				btn.setText(task.getName());
				btn.setTag(task.getId());
				m_lnTimeSheet.addView(btn);
			}
		}
		if (m_lstTimeSheetTracking.size() == 0) {
			TrackingEntry entry = new TrackingEntry();
			entry.setUser_id(Util.DEFAULT_USER_ID);
			entry.setDuration(0);
			entry.setDate(m_dayTracking);
			TimeTrackerContentProvider.TrackingEntryTable.insertEntry(
					m_resolver, entry);
		}
		int notLogYet = Util.WORKING_HOURS - count;
		if (notLogYet != 0) {
			Button btn = new Button(this);
			btn.setOnClickListener(this);
			btn.setHeight(notLogYet * hourSize);
			btn.setText("+");
			btn.setTag(Util.CREATE);
			btn.setLayoutParams(layoutParams);
			btn.setBackgroundColor(this.getResources().getColor(R.color.red));
			m_lnTimeSheet.addView(btn);
		}
	}

	private void fillTimeSheetTracking() throws ParseException {
		m_lnTimeSheet.removeAllViews();
		m_oneHourSize = m_scrollView.getHeight() / 8;
		addViewtoTimeSheet(m_oneHourSize);
	}

	private void getPreviousDay() {
		layoutParams.setMargins(0, 5, 5, 3);
		m_lnPreviousDay.removeAllViews();
		m_lstPreviousTimeSheet = TimeTrackerContentProvider.TrackingEntryTable
				.getEntries(m_resolver, Util.formatDate(Util.getPreviousDay()));
		if (m_lstPreviousTimeSheet != null) {
			for (int i = 0; i < m_lstPreviousTimeSheet.size(); i++) {
				m_durationPrevious += m_lstPreviousTimeSheet.get(i)
						.getDuration();
				for (int j = 0; j < m_lstPreviousTimeSheet.get(i).getDuration(); j++) {
					TextView view = new TextView(this);
					view.setHeight(5);
					view.setBackgroundColor(this.getResources().getColor(
							R.color.green));
					view.setLayoutParams(layoutParams);
					m_lnPreviousDay.addView(view);
				}
			}
			for (int i = 0; i < Util.WORKING_HOURS - m_durationPrevious; i++) {
				TextView view = new TextView(this);
				view.setHeight(5);
				view.setBackgroundColor(this.getResources().getColor(
						R.color.red));
				view.setLayoutParams(layoutParams);
				m_lnPreviousDay.addView(view);
			}
		}
	}

	private List<List<TrackingEntry>> getHistoryList() throws ParseException {
		m_sortEntriesbyDay.clear();
		List<TrackingEntry> entries = TimeTrackerContentProvider.TrackingEntryTable
				.getHistoricalEntries(m_resolver);

		Map<Date, List<TrackingEntry>> map = new TreeMap<Date, List<TrackingEntry>>(
				new Comparator<Date>() {
					public int compare(Date lhs, Date rhs) {
						return rhs.compareTo(lhs);
					}
				});

		for (TrackingEntry item : entries) {
			Date date = item.getDate();
			List<TrackingEntry> lst = map.get(date);
			if (lst == null) {
				lst = new ArrayList<TrackingEntry>();
				map.put(date, lst);
			}
			lst.add(item);
		}

		for (Entry<Date, List<TrackingEntry>> entry : map.entrySet()) {
			m_sortEntriesbyDay.add(entry.getValue());
		}

		return m_sortEntriesbyDay;
	}

	private int getHistoryPecent() {
		int percent = 0;
		int size = m_sortEntriesbyDay.size();
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < m_sortEntriesbyDay.get(i).size(); j++) {
				percent += m_sortEntriesbyDay.get(i).get(j).getDuration();
			}
		}
		return (size > 0) ? ((percent * 100) / (Util.WORKING_HOURS * size)) : 0;
	}

	public void onClick(View v) {
		Button btn = (Button) v;
		if (btn.getTag().equals(Util.CREATE)) {
			Intent intent = new Intent(MainActivity.this,
					RecordWorkActivity.class);
			intent.putExtra(Util.ACTION, Util.CREATE);
			intent.putExtra(Util.TIME_SHEET_TRACKING,
					(Serializable) m_lstTimeSheetTracking);
			intent.putExtra(Util.DAY_TO_RECORD, Util.dfm.format(m_dayTracking));
			startActivityForResult(intent, RecordWorkActivity.REQUEST_CODE);
		} else {
			Intent intent = new Intent(MainActivity.this,
					RecordWorkActivity.class);
			intent.putExtra("Task_Name", btn.getText().toString());
			intent.putExtra("Task_Id", btn.getTag().toString());
			intent.putExtra(Util.TIME_SHEET_TRACKING,
					(Serializable) m_lstTimeSheetTracking);
			intent.putExtra(Util.DAY_TO_RECORD, Util.dfm.format(m_dayTracking));
			intent.putExtra(Util.ACTION, Util.EDIT);
			startActivityForResult(intent, RecordWorkActivity.REQUEST_CODE);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.addTask:
			Intent intent = new Intent(MainActivity.this,
					RecordWorkActivity.class);
			intent.putExtra(Util.TIME_SHEET_TRACKING,
					(Serializable) m_lstTimeSheetTracking);
			intent.putExtra(Util.DAY_TO_RECORD, Util.dfm.format(m_dayTracking));
			intent.putExtra(Util.ACTION, Util.CREATE);
			startActivityForResult(intent, RecordWorkActivity.REQUEST_CODE);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		try {
			fillTimeSheetTracking();
		} catch (ParseException e) {
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if ((requestCode == RecordWorkActivity.REQUEST_CODE && resultCode == Util.ACTION_CLOSE)
				|| (requestCode == PreviousActivity.REQUEST_CODE && resultCode == Util.ACTION_CLOSE)
				|| (requestCode == HistoryActivity.REQUEST_CODE && resultCode == Util.ACTION_CLOSE)) {
			finish();
		}
	}
}
